package ar.edu.uba.fi.jmit.consolevisualizer;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.json.JSONArray;

import ar.edu.uba.fi.jmit.receiver.Receiver;
import ar.edu.uba.fi.jmit.receiver.ReceiverFactory;

public class ConsoleVisualizerInitializerServlet extends HttpServlet{
	
	private static final long serialVersionUID = 510637779957650747L;
	private Logger logger;
	
	public ConsoleVisualizerInitializerServlet() {
		super();
		this.logger = Logger.getLogger(this.getClass());
	}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		logger.info("Initializing Console Visualizer");
		Receiver receiver = ReceiverFactory.getInstance().getReceiver("receiver");
		addObservers(receiver);
	}
	
	private void post(HttpServletResponse resp, String txt) throws IOException {
		resp.getOutputStream().print(txt + "\n");
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("Doing Get on ConsoleVisualizer");
		String dataType = req.getParameter("type");
		if(dataType == null || dataType.equals("html")) {
			this.postHtml(resp);
		}else if(dataType.equals("json")) {
			this.postJson(resp);
		}
	}
	
	private void postJson(HttpServletResponse resp) throws IOException {
		JSONArray array = new JSONArray(ConsoleVisualizerManager.getInstance().getMessages());
		resp.getOutputStream().print(array.toString());
	}

	private void postHtml(HttpServletResponse resp) throws IOException {
		int nro = 1;
		for (String message : ConsoleVisualizerManager.getInstance().getMessages()) {
			post(resp, nro++ + ") " + message);
		}
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.info("Doing Post on ConsoleVisualizer");
		doGet(req, resp);
	}
	
	protected void addObservers(Receiver receiver) {
		logger.info("Adding Console Visualizer");
		receiver.addObserver(ConsoleVisualizerManager.getInstance());
	}
}
